<?php

namespace App\Http\Service;

use App\Http\Controllers\api\IntegralController;
use App\Repository\Repositories\IntegralRepositories;
use App\Repository\RepositoryInterface\IntegralInterface;
use Illuminate\Support\Facades\DB;
use Illuminate\Validation\ValidationException;

class Integral
{

    protected $integral;

    public function __construct(IntegralInterface $integral){
        $this->integral = $integral;
    }

    /**
     * @param $uid
     * @return mixed|string
     * 用户剩余积分
     */
    public static function userRemainderIntegral($uid)
    {
        try {
            $user_integral_balance = (new IntegralRepositories())->userIntegralBalance($uid);
            return $user_integral_balance;
        }catch (ValidationException $validationException){
            return $validationException->getFile();
        }
    }

    /**
     * @param $is_integral_goods
     * @return array
     * 可兑换商品所需积分、详情
     */
    public static function consumeIntegral($is_integral_goods)
    {
        try {
            $points_required = [];
            foreach ($is_integral_goods as $value){
                if ($value->price <=5){//价格过低不予兑换
                    continue;
                }
                $points_required['price'] = round($value->price*20/100)*100;//兑换商品积分取整百(所需积分)
                $points_required['goods'] = $value;//商品详情
                $points_required_all[] = $points_required;//所有数据
            }
            return $points_required_all;
        }catch (ValidationException $validationException){
            return $validationException->getFile();
        }
    }

    /**
     * @param $user_id
     * 用户id
     * @param $integral_exchange_goods
     * 兑换物品积分
     * @param $user_integral_balance
     * 用户剩余积分
     * @return string
     * 积分兑换接口
     */
    public static function userIntegralBalance($user_id,$integral_exchange_goods,$user_integral_balance)
    {
        try {
            DB::beginTransaction();
            if ($user_integral_balance < $integral_exchange_goods){
                return '对不起，您的积分不足';
            }
            //用户积分扣除
            $user_integral_buckle = (new IntegralRepositories())->userIntegralBuckle($user_id,$integral_exchange_goods,$user_integral_balance);
            //用户积分变动记录
            $user_integral_fluctuation_recording = (new IntegralRepositories())->integralFluctuationRecording($user_id,'3',$integral_exchange_goods);
            DB::commit();
            if ($user_integral_buckle && $user_integral_fluctuation_recording){
                return '兑换成功';
            }else{
                return '兑换出错，请联系管理员';
            }
        }catch (ValidationException $validationException){
            DB::rollBack();
            return $validationException->getFile();
        }
    }
}
